<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ARQ文件上传系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            padding: 20px;
        }
        .upload-container {
            max-width: 800px;
            margin: 0 auto;
        }
        .upload-area {
            border: 2px dashed #ddd;
            border-radius: 5px;
            padding: 25px;
            text-align: center;
            margin-bottom: 20px;
            background-color: #f8f9fa;
            cursor: pointer;
        }
        .upload-area:hover {
            background-color: #e9ecef;
        }
        .file-list {
            margin-top: 20px;
        }
        .file-item {
            margin-bottom: 10px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .progress {
            margin-top: 8px;
            height: 5px;
        }
        .task-container {
            margin-top: 30px;
        }
        .task-item {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: #f8f9fa;
        }
        .hidden {
            display: none;
        }
        .task-actions {
            display: flex;
            gap: 5px;
            margin-left: 10px;
        }
        .file-actions {
            margin-left: 10px;
            display: flex;
            gap: 5px;
        }
        .badge {
            min-width: 70px;
            text-align: center;
        }
        .file-url {
            margin-top: 5px;
            font-size: 0.85rem;
            word-break: break-all;
        }
        .file-url a {
            color: #007bff;
            text-decoration: none;
        }
        .file-url a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container upload-container">
        <h1 class="mb-4">ARQ文件上传系统</h1>
        
        <div class="upload-area" id="uploadArea">
            <h5>拖放文件到这里或点击选择文件</h5>
            <p class="text-muted">支持多文件上传</p>
            <input type="file" id="fileInput" multiple class="hidden">
        </div>
        
        <div class="file-list" id="selectedFiles">
            <h5>已选择的文件：</h5>
            <div id="fileItems"></div>
        </div>
        
        <!-- 隐藏上传按钮而不是移除 -->
        <div class="d-grid gap-2" style="display: none;">
            <button class="btn btn-primary" id="uploadButton" disabled>上传文件</button>
        </div>
        
        <div class="task-container" id="tasksContainer">
            <h3>上传任务</h3>
            <div id="taskItems"></div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const uploadArea = document.getElementById('uploadArea');
            const fileInput = document.getElementById('fileInput');
            const fileItems = document.getElementById('fileItems');
            const uploadButton = document.getElementById('uploadButton');
            const taskItems = document.getElementById('taskItems');
            
            // API路径
            const UPLOAD_API = '/router_upload/upload/';
            const STATUS_API = '/router_upload/status/';
            const PAUSE_API = '/router_upload/pause/';
            const RESUME_API = '/router_upload/resume/';
            const DELETE_TASK_API = '/router_upload/task/';
            const DELETE_FILE_API = '/router_upload/file/';
            const DOWNLOAD_API = '/router_upload/download/';
            
            // 存储选择的文件
            let selectedFiles = [];
            // 存储任务信息
            let tasks = {};
            // 存储轮询间隔ID
            let pollIntervals = {};
            
            // 点击上传区域触发文件选择
            uploadArea.addEventListener('click', function() {
                fileInput.click();
            });
            
            // 拖放文件功能
            uploadArea.addEventListener('dragover', function(e) {
                e.preventDefault();
                uploadArea.style.backgroundColor = '#e9ecef';
            });
            
            uploadArea.addEventListener('dragleave', function(e) {
                e.preventDefault();
                uploadArea.style.backgroundColor = '#f8f9fa';
            });
            
            uploadArea.addEventListener('drop', function(e) {
                e.preventDefault();
                uploadArea.style.backgroundColor = '#f8f9fa';
                
                const files = e.dataTransfer.files;
                handleSelectedFiles(files);
                
                // 自动开始上传
                if (files.length > 0) {
                    uploadFiles();
                }
            });
            
            // 处理选择的文件
            fileInput.addEventListener('change', function() {
                handleSelectedFiles(this.files);
                
                // 自动开始上传
                if (this.files.length > 0) {
                    uploadFiles();
                }
            });
            
            // 文件选择处理函数
            function handleSelectedFiles(files) {
                if (files.length === 0) return;
                
                selectedFiles = Array.from(files);
                renderSelectedFiles();
                uploadButton.disabled = false;
            }
            
            // 渲染选择的文件列表
            function renderSelectedFiles() {
                fileItems.innerHTML = '';
                
                selectedFiles.forEach((file, index) => {
                    const fileItem = document.createElement('div');
                    fileItem.className = 'file-item';
                    
                    const fileSize = formatFileSize(file.size);
                    
                    fileItem.innerHTML = `
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <strong>${file.name}</strong>
                                <div class="text-muted small">${fileSize}</div>
                            </div>
                            <button class="btn btn-sm btn-outline-danger remove-file" data-index="${index}">移除</button>
                        </div>
                    `;
                    
                    fileItems.appendChild(fileItem);
                });
                
                // 添加文件移除事件监听器
                document.querySelectorAll('.remove-file').forEach(button => {
                    button.addEventListener('click', function() {
                        const index = parseInt(this.getAttribute('data-index'));
                        selectedFiles.splice(index, 1);
                        renderSelectedFiles();
                        
                        if (selectedFiles.length === 0) {
                            uploadButton.disabled = true;
                        }
                    });
                });
            }
            
            // 上传文件按钮点击事件
            uploadButton.addEventListener('click', function() {
                uploadFiles();
            });
            
            // 上传文件到服务器
            function uploadFiles() {
                if (selectedFiles.length === 0) return;
                
                const formData = new FormData();
                selectedFiles.forEach(file => {
                    formData.append('files', file);
                });
                
                uploadButton.disabled = true;
                uploadButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 上传中...';
                
                fetch(UPLOAD_API, {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('上传失败');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('上传成功:', data);
                    
                    // 重置文件选择
                    selectedFiles = [];
                    fileItems.innerHTML = '';
                    
                    // 创建任务项并开始轮询状态
                    createTaskItem(data.task_id);
                    
                    // 轮询任务状态
                    pollTaskStatus(data.task_id);
                })
                .catch(error => {
                    console.error('上传错误:', error);
                    alert('上传失败: ' + error.message);
                })
                .finally(() => {
                    uploadButton.disabled = false;
                    uploadButton.innerHTML = '上传文件';
                });
            }
            
            // 创建任务项显示
            function createTaskItem(taskId) {
                const taskDiv = document.createElement('div');
                taskDiv.className = 'task-item';
                taskDiv.id = `task-${taskId}`;
                
                taskDiv.innerHTML = `
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="d-flex align-items-center">
                            <h5 class="mb-0">任务 ID: ${taskId.substr(0, 8)}...</h5>
                            <div class="task-actions">
                                <button class="btn btn-sm btn-warning pause-task" data-task-id="${taskId}">暂停</button>
                                <button class="btn btn-sm btn-info resume-task hidden" data-task-id="${taskId}">恢复</button>
                                <button class="btn btn-sm btn-danger delete-task" data-task-id="${taskId}">删除</button>
                            </div>
                        </div>
                        <span class="badge bg-info">进行中</span>
                    </div>
                    <div class="mt-2">
                        <div class="d-flex justify-content-between">
                            <span>总体进度:</span>
                            <span id="task-${taskId}-progress">0%</span>
                        </div>
                        <div class="progress">
                            <div class="progress-bar" id="task-${taskId}-progressbar" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                    </div>
                    <div class="mt-3">
                        <h6>文件进度:</h6>
                        <div id="task-${taskId}-files"></div>
                    </div>
                `;
                
                taskItems.prepend(taskDiv);
                
                // 初始化任务状态对象
                tasks[taskId] = {
                    element: taskDiv,
                    files: {}
                };
                
                // 添加暂停/恢复/删除任务事件监听器
                addTaskActionListeners(taskId);
            }
            
            // 添加任务操作事件监听器
            function addTaskActionListeners(taskId) {
                const taskElement = document.getElementById(`task-${taskId}`);
                
                // 暂停任务
                const pauseBtn = taskElement.querySelector('.pause-task');
                if (pauseBtn) {
                    pauseBtn.addEventListener('click', function() {
                        pauseTask(taskId);
                    });
                }
                
                // 恢复任务
                const resumeBtn = taskElement.querySelector('.resume-task');
                if (resumeBtn) {
                    resumeBtn.addEventListener('click', function() {
                        resumeTask(taskId);
                    });
                }
                
                // 删除任务
                const deleteBtn = taskElement.querySelector('.delete-task');
                if (deleteBtn) {
                    deleteBtn.addEventListener('click', function() {
                        if (confirm('确定要删除此任务吗？这将停止所有处理并删除上传的文件。')) {
                            deleteTask(taskId);
                        }
                    });
                }
            }
            
            // 暂停任务
            function pauseTask(taskId) {
                fetch(`${PAUSE_API}${taskId}`, {
                    method: 'POST'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('暂停失败');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('任务暂停结果:', data);
                    if (data.success) {
                        // 更新UI
                        const taskElement = document.getElementById(`task-${taskId}`);
                        const pauseBtn = taskElement.querySelector('.pause-task');
                        const resumeBtn = taskElement.querySelector('.resume-task');
                        const statusBadge = taskElement.querySelector('.badge');
                        
                        pauseBtn.classList.add('hidden');
                        resumeBtn.classList.remove('hidden');
                        statusBadge.className = 'badge bg-warning';
                        statusBadge.textContent = '已暂停';
                    } else {
                        alert(`暂停失败: ${data.message}`);
                    }
                })
                .catch(error => {
                    console.error('暂停错误:', error);
                    alert('暂停任务失败: ' + error.message);
                });
            }
            
            // 恢复任务
            function resumeTask(taskId) {
                fetch(`${RESUME_API}${taskId}`, {
                    method: 'POST'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('恢复失败');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('任务恢复结果:', data);
                    if (data.success) {
                        // 更新UI
                        const taskElement = document.getElementById(`task-${taskId}`);
                        const pauseBtn = taskElement.querySelector('.pause-task');
                        const resumeBtn = taskElement.querySelector('.resume-task');
                        const statusBadge = taskElement.querySelector('.badge');
                        
                        pauseBtn.classList.remove('hidden');
                        resumeBtn.classList.add('hidden');
                        statusBadge.className = 'badge bg-info';
                        statusBadge.textContent = '进行中';
                    } else {
                        alert(`恢复失败: ${data.message}`);
                    }
                })
                .catch(error => {
                    console.error('恢复错误:', error);
                    alert('恢复任务失败: ' + error.message);
                });
            }
            
            // 删除任务
            function deleteTask(taskId) {
                fetch(`${DELETE_TASK_API}${taskId}`, {
                    method: 'DELETE'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('删除失败');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('任务删除结果:', data);
                    if (data.success) {
                        // 停止轮询
                        if (pollIntervals[taskId]) {
                            clearInterval(pollIntervals[taskId]);
                            delete pollIntervals[taskId];
                        }
                        
                        // 从任务列表中移除
                        const taskElement = document.getElementById(`task-${taskId}`);
                        if (taskElement) {
                            taskElement.remove();
                        }
                        
                        // 从tasks对象中删除
                        if (tasks[taskId]) {
                            delete tasks[taskId];
                        }
                    } else {
                        alert(`删除失败: ${data.message}`);
                    }
                })
                .catch(error => {
                    console.error('删除错误:', error);
                    alert('删除任务失败: ' + error.message);
                });
            }
            
            // 删除单个文件
            function deleteFile(taskId, fileId, fileElement) {
                fetch(`${DELETE_FILE_API}${taskId}/${fileId}`, {
                    method: 'DELETE'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('删除文件失败');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('文件删除结果:', data);
                    if (data.success) {
                        // 从UI中移除文件项
                        if (fileElement) {
                            fileElement.remove();
                        }
                        
                        // 检查是否整个任务都被删除了
                        if (data.message.includes('任务已清空')) {
                            // 停止轮询
                            if (pollIntervals[taskId]) {
                                clearInterval(pollIntervals[taskId]);
                                delete pollIntervals[taskId];
                            }
                            
                            // 从任务列表中移除
                            const taskElement = document.getElementById(`task-${taskId}`);
                            if (taskElement) {
                                taskElement.remove();
                            }
                            
                            // 从tasks对象中删除
                            if (tasks[taskId]) {
                                delete tasks[taskId];
                            }
                        }
                    } else {
                        alert(`删除文件失败: ${data.message}`);
                    }
                })
                .catch(error => {
                    console.error('删除文件错误:', error);
                    alert('删除文件失败: ' + error.message);
                });
            }
            
            // 轮询任务状态
            function pollTaskStatus(taskId) {
                // 清除之前的轮询
                if (pollIntervals[taskId]) {
                    clearInterval(pollIntervals[taskId]);
                }
                
                pollIntervals[taskId] = setInterval(() => {
                    fetch(`${STATUS_API}${taskId}`)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('获取状态失败');
                            }
                            return response.json();
                        })
                        .then(data => {
                            // 更新任务UI
                            updateTaskUI(taskId, data);
                            
                            // 如果任务已完成、失败或暂停，停止轮询
                            if (data.status === 'completed' || data.status === 'failed' || data.status === 'paused') {
                                clearInterval(pollIntervals[taskId]);
                                delete pollIntervals[taskId];
                                
                                // 如果任务已暂停，更新UI
                                if (data.status === 'paused') {
                                    const taskElement = document.getElementById(`task-${taskId}`);
                                    const pauseBtn = taskElement.querySelector('.pause-task');
                                    const resumeBtn = taskElement.querySelector('.resume-task');
                                    
                                    pauseBtn.classList.add('hidden');
                                    resumeBtn.classList.remove('hidden');
                                }
                            }
                        })
                        .catch(error => {
                            console.error('获取状态错误:', error);
                            clearInterval(pollIntervals[taskId]);
                            delete pollIntervals[taskId];
                        });
                }, 1000); // 每秒轮询一次
            }
            
            // 更新任务UI
            function updateTaskUI(taskId, taskData) {
                if (!tasks[taskId]) return;
                
                const taskElement = document.getElementById(`task-${taskId}`);
                if (!taskElement) return;
                
                const progressElement = document.getElementById(`task-${taskId}-progress`);
                const progressBarElement = document.getElementById(`task-${taskId}-progressbar`);
                const filesElement = document.getElementById(`task-${taskId}-files`);
                
                // 更新总进度
                const progress = taskData.progress || 0;
                progressElement.textContent = `${progress}%`;
                progressBarElement.style.width = `${progress}%`;
                progressBarElement.setAttribute('aria-valuenow', progress);
                
                // 更新状态标签
                const statusBadge = taskElement.querySelector('.badge');
                if (taskData.status === 'completed') {
                    statusBadge.className = 'badge bg-success';
                    statusBadge.textContent = '已完成';
                    
                    // 隐藏暂停/恢复按钮
                    const pauseBtn = taskElement.querySelector('.pause-task');
                    const resumeBtn = taskElement.querySelector('.resume-task');
                    pauseBtn.classList.add('hidden');
                    resumeBtn.classList.add('hidden');
                    
                } else if (taskData.status === 'failed') {
                    statusBadge.className = 'badge bg-danger';
                    statusBadge.textContent = '失败';
                    
                    // 隐藏暂停/恢复按钮
                    const pauseBtn = taskElement.querySelector('.pause-task');
                    const resumeBtn = taskElement.querySelector('.resume-task');
                    pauseBtn.classList.add('hidden');
                    resumeBtn.classList.add('hidden');
                    
                } else if (taskData.status === 'paused') {
                    statusBadge.className = 'badge bg-warning';
                    statusBadge.textContent = '已暂停';
                    
                    // 显示恢复按钮，隐藏暂停按钮
                    const pauseBtn = taskElement.querySelector('.pause-task');
                    const resumeBtn = taskElement.querySelector('.resume-task');
                    pauseBtn.classList.add('hidden');
                    resumeBtn.classList.remove('hidden');
                }
                
                // 更新文件进度
                if (taskData.files) {
                    filesElement.innerHTML = '';
                    
                    Object.entries(taskData.files).forEach(([fileId, file]) => {
                        const fileItemDiv = document.createElement('div');
                        fileItemDiv.className = 'file-item';
                        fileItemDiv.setAttribute('data-file-id', fileId);
                        
                        // 设置文件状态样式
                        let statusClass = 'bg-info';
                        let statusText = '队列中';
                        
                        if (file.status === 'processing') {
                            statusClass = 'bg-primary';
                            statusText = '处理中';
                        } else if (file.status === 'completed') {
                            statusClass = 'bg-success';
                            statusText = '已完成';
                        } else if (file.status === 'failed') {
                            statusClass = 'bg-danger';
                            statusText = '失败';
                        } else if (file.status === 'paused') {
                            statusClass = 'bg-warning';
                            statusText = '已暂停';
                        }
                        
                        // 构建文件项HTML
                        let fileHtml = `
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <strong>${file.original_filename}</strong>
                                    <div class="text-muted small">${formatFileSize(file.size)}</div>
                                </div>
                                <div class="d-flex align-items-center">
                                    <span class="badge ${statusClass}">${statusText}</span>
                                    <div class="file-actions">
                        `;
                        
                        // 添加文件操作按钮
                        if (file.status !== 'completed') {
                            fileHtml += `<button class="btn btn-sm btn-outline-danger delete-file" data-task-id="${taskId}" data-file-id="${fileId}">删除</button>`;
                        }
                        
                        // 如果文件已完成，添加下载按钮
                        if (file.status === 'completed' && file.file_url) {
                            fileHtml += `
                                <a href="${file.file_url}" class="btn btn-sm btn-outline-primary" download="${file.original_filename}" target="_blank">下载</a>
                                <button class="btn btn-sm btn-outline-secondary copy-url" data-url="${file.file_url}">复制链接</button>
                            `;
                        }
                        
                        fileHtml += `
                                    </div>
                                </div>
                            </div>
                            <div class="mt-2">
                                <div class="d-flex justify-content-between">
                                    <span>进度:</span>
                                    <span>${file.progress || 0}%</span>
                                </div>
                                <div class="progress">
                                    <div class="progress-bar" role="progressbar" style="width: ${file.progress || 0}%" aria-valuenow="${file.progress || 0}" aria-valuemin="0" aria-valuemax="100"></div>
                                </div>
                            </div>
                        `;
                        
                        // 如果有文件URL，显示链接
                        if (file.file_url) {
                            fileHtml += `
                                <div class="file-url">
                                    <small>文件URL: <a href="${file.file_url}" target="_blank">${file.file_url}</a></small>
                                </div>
                            `;
                        }
                        
                        fileItemDiv.innerHTML = fileHtml;
                        filesElement.appendChild(fileItemDiv);
                        
                        // 添加删除文件按钮事件监听
                        const deleteFileBtn = fileItemDiv.querySelector('.delete-file');
                        if (deleteFileBtn) {
                            deleteFileBtn.addEventListener('click', function() {
                                const fileId = this.getAttribute('data-file-id');
                                const taskId = this.getAttribute('data-task-id');
                                if (confirm('确定要删除此文件吗？')) {
                                    deleteFile(taskId, fileId, fileItemDiv);
                                }
                            });
                        }
                        
                        // 添加复制URL按钮事件监听
                        const copyUrlBtn = fileItemDiv.querySelector('.copy-url');
                        if (copyUrlBtn) {
                            copyUrlBtn.addEventListener('click', function() {
                                const url = this.getAttribute('data-url');
                                copyToClipboard(url);
                                alert('URL已复制到剪贴板!');
                            });
                        }
                    });
                }
            }
            
            // 复制文本到剪贴板
            function copyToClipboard(text) {
                const textArea = document.createElement("textarea");
                textArea.value = text;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
            }
            
            // 格式化文件大小显示
            function formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }
        });
    </script>
</body>
</html> 